package com.hjl.spring6.jdbc;

import org.aspectj.weaver.ast.Var;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

import java.sql.ResultSet;
import java.util.List;

/**
 * @author ServivE
 * @version 0.1
 * @className JdbcTemplateTest
 * @description
 * @date 2024/8/7 19:50
 * @since jdk11
 */
@SpringJUnitConfig(locations = "classpath:beans.xml")
public class JdbcTemplateTest {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    //测试增删改功能
    public void testUpdate() {
      /*  //增加
        //1.编写sql语句
        String sql = "insert into emp(ename,esex,sal) values (?,?,?)";
        //2 调用jdbcTemplate的方法，传入相关参数
        int i = jdbcTemplate.update(sql,"东方不败","男",3600);
        System.out.println(i);*/

        /*//修改
        String sql = "update emp set ename = ? where eid =?";
        jdbcTemplate.update(sql, "东方不败2.0", 42);*/
        //删除
        String sql = "delete from emp where eid = ?";
        jdbcTemplate.update(sql, 42);
    }

    //查询:返回对象
    @Test
    public void testObject() {
        String sql = "select * from emp where eid = ?";
        // 实现RowMapper接口的方法
        // rs  resultSet结果集对象
        // rowNum  行号
        /*写法一
        Emp empResult = jdbcTemplate.queryForObject(sql, (rs, rowNum) -> {
            Emp emp = new Emp();
            emp.setEid(rs.getInt("eid"));
            emp.setEname(rs.getString("ename"));
            emp.setEsex(rs.getString("esex"));
            emp.setHiredate(rs.getDate("hiredate"));
            emp.setSal(rs.getString("sal"));
            return emp;
        }, 4);
        System.out.println(empResult);*/
        //写法二
        Emp emp = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Emp.class), 4);
        System.out.println(emp);
    }

    @Test
    //查询:返回list集合
    public void testSelectList() {
        String sql = "select * from emp";
        List<Emp> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Emp.class));
        System.out.println(list);
    }

    //查询:返回单个值
    @Test
    public void testSelectValue() {
        String sql = "select count(*) from emp";
        Integer i = jdbcTemplate.queryForObject(sql, Integer.class);
        System.out.println(i);
    }


}
